package com.hty.locusmap;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import android.app.Activity;
import android.app.Notification;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

public class NoMapMode extends Activity {
	LocationClient mLocationClient;
	boolean isFirstLoc = true;
	TextView textView1, textView2;
	LatLng p1, p2;
	double lc = 0, speed, speedmax = 0, ltt, lgt, ltt1, lgt1, alt, distance, distancesend = 0;
	Date date, time_start;
	long duration;
	SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
	SimpleDateFormat timeformatd = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
	SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
	SimpleDateFormat dateformat2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
	String c, sduration, filename="";
	int ER, d = 0, lci;
	Notification mNotification;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MainApplication.getInstance().addActivity(this);
		MainApplication.mContext = this;
		MainApplication.mode = "nomap";
		timeformat.setTimeZone(TimeZone.getDefault());
		timeformatd.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_nomap);
		textView1 = (TextView) findViewById(R.id.textView_info);
		textView2 = (TextView) findViewById(R.id.textView_copyright);
		MyLocationListenner myLocationListener = new MyLocationListenner();
		mLocationClient = new LocationClient(this);
		mLocationClient.registerLocationListener(myLocationListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setScanSpan(5000);
		mLocationClient.setLocOption(option);
		initNotification();
		mLocationClient.enableLocInForeground(1, mNotification);
		mLocationClient.start();
		date = new Date();
		time_start = date;
		RWXML.create(dateformat1.format(time_start));
		filename = dateformat1.format(time_start) + "BD.gpx";
	}

	@Override
	protected void onDestroy() {
		mLocationClient.stop();
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "退出");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int item_id = item.getItemId();
		switch (item_id) {
		case 0:
			MainApplication.wfp = "";
			MainApplication.mode = "";
			finish();
			startActivity(new Intent(NoMapMode.this, MenuActivity.class));
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(NoMapMode.this, MenuActivity.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	class MyLocationListenner extends BDAbstractLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null) {
				return;
			}
			date = new Date();
			duration = date.getTime() - time_start.getTime();
			ltt = location.getLatitude();
			lgt = location.getLongitude();
			BigDecimal BD = BigDecimal.valueOf(location.getSpeed());
			speed = BD.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			BD = BigDecimal.valueOf(location.getAltitude());
			alt = BD.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			p1 = new LatLng(ltt, lgt);
			if (isFirstLoc) {
				p2 = p1;
				ltt1 = ltt;
				lgt1 = lgt;
				isFirstLoc = false;
			}
			BigDecimal bd2 = BigDecimal.valueOf(DistanceUtil.getDistance(p1, p2));
			distance = bd2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			ER = Math.round(location.getRadius());
			if (ER > 0 && ER < 100) {
				if (speed > speedmax)
					speedmax = speed;
				ltt1 = ltt;
				lgt1 = lgt;
				p2 = p1;
				String sdistance = String.valueOf(distance);
				if (!sdistance.contains("E")) {
					lc += distance;
					distancesend = distance;
				}
				sduration = timeformatd.format(duration);
				new Thread(t).start();
				String sltt = String.valueOf(ltt);
				String slgt = String.valueOf(lgt);
				if (!sltt.contains("E") && !slgt.contains("E") && distance < 200) {
					RWXML.add(filename, dateformat.format(date), sltt, slgt, String.valueOf(alt), String.valueOf(speed), String.valueOf(lc), timeformatd.format(duration));
				}
				lci = (int) lc;
			}
			textView1.setText(location.getTime() + "\nLocType：" + location.getLocType() + "\n纬度：" + ltt + "\n经度：" + lgt + "\n误差半径：" + ER + "米" + "\n速度：" + speed	+ "米/秒" + "\n位移：" + distance + "米" + "\n卫星数目：" + location.getSatelliteNumber() + "\n地址：" + location.getAddrStr());
			textView2.setText("开始时间：" + timeformat.format(time_start) + "\n时长：" + sduration + "\n路程：" + lci + "米\n速度：" + speed + "米/秒\n最大速度：" + speedmax + "米/秒\n方向：" + location.getDirection() + "\n上传：" + c);
			distance = 0;
		}
	}

	Thread t = new Thread() {
		@Override
		public void run() {
			String dateu = "";
			String timeu = "";
			try {
				dateu = URLEncoder.encode(dateformat2.format(date), "utf-8");
				timeu = URLEncoder.encode(timeformat.format(date), "utf-8");
			} catch (Exception e) {
				Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
			}
			Log.e(Thread.currentThread().getStackTrace()[2] + "", "误差半径：" + ER);
			if (ER > 0 && ER < 100)
				c = Utils.sendURLResponse("http://sonichy.hjwhp.ghco.info/locusmap/add.php?date=" + dateu + "&time=" + timeu + "&longitude=" + lgt + "&latitude=" + ltt + "&speed=" + speed + "&distance=" + distancesend);
			distancesend = 0;
		}
	};

	void initNotification() {
		//设置后台定位
		//Android 8.0 及以上使用 NotificationUtils
		NotificationUtils notificationUtils = new NotificationUtils(this);
		Notification.Builder builder = notificationUtils.getAndroidChannelNotification("轨迹地图", "正在定位");
		mNotification = builder.build();
		mNotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
	}

}
